<?php

namespace app\controller\frontend;

use app\model\BigField;
use app\model\Category;
use app\model\Theme;
use app\model\ThemeFile;
use app\model\WebsiteSetting;
use app\validate\DesignValidate;
use think\exception\ValidateException;

class DesignController extends DesignBaseController
{
    public function index()
    {
        $param = $this->request->param();
        $param['html'] = $param['html'] ?? '';
        // 数据验证
        try{
            validate(DesignValidate::class)->scene('index')->check($param);
        }catch(ValidateException $e){
            return jsonReturn(-1, $e->getError());
        }

        // 获取当前站的模板目录
        $themeModel = new Theme();
        $theme = $themeModel->where([
            ['website_id', '=', $param['website_id']],
            ['lang', '=', $param['lang']],
            ['is_active', '=', 1],
        ])->value('theme');

        if (empty($theme)) {
            return jsonReturn(-1, lang('当前站点没有激活的模板，请去安装模板'));
        }

        //search for html files in demo and my-pages folders
//        $htmlFiles = glob("{design/designPage/*\/*.html,design/designPage/*.html,design/demo/*\/*.html,design/demo/*.html}", GLOB_BRACE);
//        $htmlFiles = glob("{design/designPage/*\/*.html,design/designPage/*.html}", GLOB_BRACE);
//        $htmlFiles = glob("{themes/hc_original/{$theme}/*.html,themes/hc_original/{$theme}/*\/*.html}", GLOB_BRACE);
//
//
//        $files = [];
//        foreach ($htmlFiles as $file) {
//            $file = mb_substr($file, 7);
//            $pathInfo = pathinfo($file);
//            if (in_array($pathInfo['basename'], array('new-page-blank-template.html', 'editor.html'))) continue;//skip template files
//
//            $filename = $pathInfo['filename'];
////            var_dump($filename);
//
//            $folder = preg_replace('@/.+?$@', '', $pathInfo['dirname']);
//            $subfolder = preg_replace('@^.+?/@', '', $pathInfo['dirname']);
//
//            if ($filename == 'index' && $subfolder) {
////                $filename = $subfolder;
//            }
//            $url = $pathInfo['dirname'] . '/' . $pathInfo['basename'];
//            $name = ucfirst($filename);
//
////            dump($pathInfo['basename']);
//
//            $files[] = [
//                'name' => $name,
//                'file' => $filename,
//                'title' => $name,
////                'url' => '../themes/' . $url,
//                'url' => '/' . $pathInfo['basename'],
//                'folder' => '../themes/' . $folder,
//            ];
//
////            $files .= "{name:'$name', file:'$filename', title:'$name',  url: '$url', folder:'$folder'},";
//        }

        // 获取当前网站所有有模板的栏目的路由
        $category = new Category();
        $list = $category->where([
            ['website_id', '=', $param['website_id']],
            ['lang', '=', $param['lang']],
            ['type', 'in', [4]],
            ['status', '=', 1],
            ['list_tpl', '<>', ''],
        ])->field('id, title, list_tpl, alias')->group('list_tpl')->select()->toArray();

        if (empty($list)) {
            return jsonReturn(-1, lang('当前站点已安装模板，但没有栏目使用单页模板，如当前站是子站，需要编辑父站点的数据，请回后台切换至父站点'));
        }

        $files = [];
        $initPage = '';
        foreach ($list as $value) {
            $pathInfo = pathinfo($value['list_tpl']);

            if ($param['html'] == $value['list_tpl']) {
                $initPage = $pathInfo['filename'];
            }

            $file = [
                'name' => $pathInfo['filename'],
                'file' => $value['list_tpl'],
                'title' => $value['list_tpl'],
//                'url' => '../themes/' . $url,
                'url' => $value['alias'],
                'folder' => $value['title'],
            ];
            $files[] = $file;
        }
//        dd($files);

        $where = [
            'website_id' => $param['website_id'],
            'lang' => $param['lang'],
        ];
        // 获取系统配置
        $websiteSetting = new WebsiteSetting();
        $res = $websiteSetting->getWebsiteSetting($where);
        $res['data'] = $res['data']->toArray();
        $setting = $res['data']['setting'];
        $initPage = $initPage ?: $files[0]['name'];

        $data = [
            'website_id' => $param['website_id'],
            'lang' => $param['lang'],
            'setting' => $setting,
            'pages' => json_encode($files),
            'init_page' => $initPage,
        ];
        $this->assign($data);

        return $this->fetchDesign('editor');
    }

    public function getDesignHtml()
    {
        $param = $this->request->param();

        return $this->fetchDesign($param['html_path']);
    }
}
